"""
Author        yongfa
Date          2023-09-05 05:40:31
LastEditTime  2023-09-08 06:14:21
LastEditors   yongfa
Description   异步任务
"""
import time
import random

from flask import current_app

from app.extensions import celery_app, db
from app.extensions.exception import EMailLoginError
from app.extensions.utils.enums import ResumeEmailTaskEnum
from app.modules.v1.resume.models import ResumeEmailTask, ResumeParserTask, EmailInfo, ResumeEmail


from app.app_celery import logger
from .emailLogin import EmailLogin
from app.app_celery.parserJobs.tasks import HandleResumeParser


@celery_app.task(bind=True, name='HandleEmailTasks', routing_key='emailTasks', priority=3)
def HandleEmailTasks(self, email_task_id: int):
    """处理邮箱任务"""
    try:
        logger.info('HandleEmailTasks: {}'.format(email_task_id))
        email_task = None
        count = 3
        while email_task is None and count > 0:
            email_task = ResumeEmailTask.get(id=email_task_id)
            time.sleep(random.random())
            count -= 1

        email_info = EmailInfo.get(id=email_task.company_email_id)

        email_login = {
            "host": email_info.email_host,
            "port": email_info.email_port,
            "user": email_info.email,
            "password": email_info.email_password,
            "protocol": email_info.email_protocol,
            "ssl": email_info.email_ssl,
        }
        status = ResumeEmailTaskEnum.SCANING.value
        message = '处理邮件中'
        filter_conditions = email_task.filter_conditions
        top_num = 5
        if filter_conditions:
            logger.info('filter_conditions: {}'.format(filter_conditions))
            top_num = filter_conditions.get('top_num', 5)
        result = EmailLogin(**email_login).get_mails(top_num=top_num)
        if isinstance(result, EMailLoginError):
            status = ResumeEmailTaskEnum.LOGIN_FAIL.value
            message = '登录失败'
            logger.info('更新任务状态为: {} {}'.format(status, message))
            email_task.update(status=status, message=message, celery_task_id=self.request.id)
            return EMailLoginError

        # 登录
        logger.info('更新任务状态为: {} {}, task_id: {}'.format(status, message, self.request.id))
        email_task.update(status=status, message=message)
        process_mail_num = 0
        email_list = []
        for email in result:
            FromList = email.get('From').split(' ')
            email_from_name = FromList[0]
            email_from = FromList[1]
            mail_id = email.get('mail_id')

            # 保存新邮件
            _email_content = {
                'email_info_id': email_info.id,
                'mail_id': email.get('mail_id'),
                'email_from': email_from,
                'email_from_name': email_from_name,
                'email_from_time': email.get('Date'),
                'email_subject': email.get('Subject'),
                'email_content': email.get('content')[1:60000],
                'file_name': ','.join([file.get('name') for file in email.get('attachments')]
                                      if email.get('attachments') else []),
                'file_local_url': ','.join([file.get('path') for file in email.get('attachments')]
                                           if email.get('attachments') else []),
            }

            _email = ResumeEmail.get(email_info_id=email_info.id, mail_id=mail_id)
            if _email:
                logger.info('email_info_id:{}, mail_id: {} 邮件已经拉取过'.format(email_info.id, mail_id))
                _email.update(**_email_content, commit=False)
            else:
                _email = ResumeEmail.create(**_email_content, commit=False)
                _email.flush()
            process_mail_num += 1
            email_list.append(_email.id)

        status = ResumeEmailTaskEnum.SCANED.value
        message = '邮件拉取完成'
        logger.info('更新任务状态为: {} {}, 处理邮件数: {}'.format(status, message, process_mail_num))
        email_task.update(
            status=status,
            message=message,
            process_mail_num=process_mail_num
        )
        for email_id in email_list:
            if current_app.config.get('CELERY_DEBUG_MODEL'):
                HandleEmailParser(email_id=email_id)
            else:
                HandleEmailParser.apply_async(args=(email_id,))
    except Exception as exc:
        db.session.rollback()
        logger.exception("拉取邮件内容失败 email_task_id: {}  retries: {} error: {}".format(
            email_task_id, self.request.retries, str(exc)))
        raise self.retry(countdown=5, max_retries=3, exc=exc)  # 下次重试5s以后，最多重试3次


# 失败重试
@celery_app.task(bind=True, name='HandleEmailParser', routing_key='EmailParser', priority=2)
def HandleEmailParser(self, email_id: int):
    """处理邮箱任务"""
    try:
        logger.info('HandleEmailParser: {}'.format(email_id))
        resume_email = None
        count = 3
        while resume_email is None and count > 0:
            resume_email = ResumeEmail.get(id=email_id)
            time.sleep(random.random())
            count -= 1

        if not resume_email:
            logger.info('email_id: {} 邮件不存在'.format(email_id))
            return EMailLoginError()

        # 根据内容处理
        email_content = resume_email.email_content
        if not email_content:
            logger.info('email_id: {} 邮件内容为空'.format(email_id))
            return EMailLoginError()
        # 解析内容
        # TODO 预处理邮件内容
        content = email_content

        # 根据附件处理
        # file_name = resume_email.file_name
        # file_local_url = resume_email.file_local_url

        # if not file_name and not file_local_url:
        #     logger.info('email_id: {} 附件为空'.format(email_id))
        #     return EMailLoginError()

        # # 读取文件， 并处理出文本
        # file_list = file_name.split(',') if file_name else []
        # for file_name in file_list:
        #     pass

        # TODO 生成解析任务
        _resume_parser_task = {
            'resume_email_id': resume_email.id,
            'company_id': 1,
            'resume_type': 0,
            'parser_text'
            'resume_text': content,
            'resume_platform': 0,  # 自定义
            'callback_url': 'https://callback.com',

        }
        # 保存解析任务
        resume_parser_task = ResumeParserTask.create(**_resume_parser_task)
        logger.info('resume_parser_task: {} 开始处理'.format(resume_parser_task.id))

        if current_app.config.get('CELERY_DEBUG_MODEL'):
            HandleResumeParser(resume_parser_task_id=resume_parser_task.id)
        else:
            celery_task_id = HandleResumeParser.apply_async(args=(resume_parser_task.id,))
            resume_parser_task.update(celery_task_id=celery_task_id)

    except Exception as exc:
        db.session.rollback()
        logger.exception("处理邮件简历内容失败 email_id: {}  retries: {} error: {}".format(
            email_id, self.request.retries, str(exc)))
        raise self.retry(countdown=5, max_retries=3, exc=exc)  # 下次重试5s以后，最多重试3次
